<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */


namespace app\index\model;


use think\Model;

class UserLottery extends Model
{
    protected $autoWriteTimestamp = 'datetime';

    public function Config(){
        return $this->hasOne(LotteryConfig::class,'id','lottery_config_id');
    }

    public function getTotalNumberAttr($value,$data) : int{
        $number = (int)$data['added_number'] + (int)$data['number'];
        $number = $number > 0 ? $number : 0;
        return (int)$number;
    }

    public static function saveLottery($lottery_config,$user,int $number){
        $userLottery = self::where('user_id',$user['id'])
            ->where('lottery_config_id',$lottery_config->id)
            ->find();
        if (empty($userLottery))
            self::create([
                'mall_id' => $user['mall_id'],
                'lottery_config_id' => $lottery_config->id,
                'user_id' => $user['id'],
                'added_number' => $number,
                'end_time' => $lottery_config->end_time,
                'status' => 1
            ]);
        else
            $userLottery->inc('added_number',$number)->update();
        \think\facade\Db::name('user_lottery_record')
            ->insert([
                'user_id' => $user['id'],
                'lottery_id' => $lottery_config->id,
                'number' => $number,
                'create_time' => now()
            ]);
    }
}